package com.zzedu.integration.fileread.impl;

import com.zzedu.integration.fileread.FileReadFactoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * PDF试卷处理器
 */
@Service
public class ReadPdfFileReadFactoryServiceImpl implements FileReadFactoryService {
    Logger log = LoggerFactory.getLogger(ReadPdfFileReadFactoryServiceImpl.class);
    static List<String> exInclude = new ArrayList<>();

    static {
        exInclude = new ArrayList<>();
        for (char letter = 'A'; letter <= 'Z'; letter++) {
            exInclude.add(String.valueOf(letter));
        }
        exInclude.add("'");
        exInclude.add("’");
    }

    @Override
    public List<String> readFile(InputStream inputStream) {
        List<String> wordAllList = new ArrayList<>();
        try (PDDocument pdDocument = Loader.loadPDF(inputStream.readAllBytes())) {
            PDFLayoutTextStripper pdfStripper = new PDFLayoutTextStripper();
            // 设置 PDFBox 解析文本时的额外参数
            pdfStripper.setSortByPosition(true);  // 按位置排序，可能有助于减少文本粘连
            pdfStripper.setWordSeparator(" ");    // 设置单词分隔符
            pdfStripper.setLineSeparator("\n");   // 让换行符正确解析
            pdfStripper.setParagraphStart("\n\n");// 段落间增加额外换行

            String text = pdfStripper.getText(pdDocument);
            log.info("PDF纯文本内容:" + text);
//            String[] words = text.split("\\s+");
//            for (String w : words) {
            List<String> wordList = extractWords(text);
            log.info("提取单词:" + wordList);
            if (CollectionUtils.isNotEmpty(wordList)) {
                wordAllList.addAll(wordList);
            }
//            }
        } catch (Exception e) {
            log.error("错误信息:" + e.getMessage());
        }finally {
            IOUtils.closeQuietly(inputStream);
        }
        return wordAllList;
    }


    private List<String> extractWords(String sentence) {
        // 使用正则表达式匹配单词
        Pattern wordPattern = Pattern.compile("\\b[a-zA-Z]+(('|’)[a-z]+)?\\b");
        Matcher matcher = wordPattern.matcher(sentence);
        List<String> wordList = new ArrayList<>();
        while (matcher.find()) {
            String w = matcher.group();
            if (StringUtils.isNotBlank(w) && !exInclude.contains(w.toUpperCase()) && !w.contains("’") && !w.contains("'")) {
                wordList.add(matcher.group());
            }
        }
        return wordList;
    }

    @Override
    public boolean isRead(String fileName) {
        return fileName.toLowerCase().endsWith(".pdf");
    }
}
